package com.example.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.function.Consumer;

// 1. 使用Order注解，设置执行顺序
@Order(-1)
@Component
@Slf4j
// 2. 要实现GlobalFilter声明全局过滤器
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //  针对个别接口进行自定义放行
        ArrayList<Object> whiteList = new ArrayList<>();
        whiteList.add("/user/sendMsg");

        String url = exchange.getRequest().getPath().toString();
        if (whiteList.contains(url)){
            log.info("发送验证码放行！");
            return chain.filter(exchange);
        }

        // 1.   获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getHeaders();
        // 2.   获取authorization参数
        String token = params.getFirst("authorization");

        // 3.   JWT校验token是否有效
        //  key 需要验证的token  value   解析token的密钥
        boolean verify = JWTUtil.verify(token, "yrh0203".getBytes());
        if (!verify){
            // 拦截
            return getVoidMono(exchange);
        }

        // 4.  获取用户信息
        JWT jwt = JWTUtil.parseToken(token);

        // 4.1 获取载荷
        JWTPayload payload = jwt.getPayload();
        if (payload==null){
            //  拦截
            return getVoidMono(exchange);
        }
        // 4.2 获取载荷里面的id字段
        Object id = payload.getClaim("id");
        Object name = payload.getClaim("name");
        if (id==null){
            // 拦截
            return getVoidMono(exchange);
        }
        //  5.  将解析到的用户信息，存放到请求头上
        //  5.1 重构一个响应对象，并设置请求头，再将id添加到请求头上
        ServerHttpRequest NewRequest = exchange.getRequest().mutate().headers(new Consumer<HttpHeaders>() {
            @Override
            public void accept(HttpHeaders httpHeaders) {
                httpHeaders.add("id", id.toString());
            }
        }).build();


        //  5.2 刷新请求头
        exchange.mutate().request(NewRequest).build();


        // 6.  放行
        log.info("放行成功！");
        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        //  获取响应结构，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //  修改后的返回值结果，响应给前端
        return exchange.getResponse().setComplete();
    }
}